<template>

  <!-- 最近访问记录 -->
  <el-card style="margin: 10px 0">
    <div class="card-header">
      <h3>最近访问记录</h3>
    </div>
    <ul class="visit-list">
      <li v-for="(item, index) in ipAddressesListRecent" :key="index" :style="getGradientStyle(index)"
          class="ip-item">
        <div class="ip-info">
          <span class="ip-address">{{ item.ip_address }}</span>
          <span class="province">({{ item.province }})</span>
        </div>
        <div class="visit-info">
          <span class="time">{{ formatPast(item.update_time) }}</span>
          <span class="page-access">访问了页面</span>
        </div>
      </li>
    </ul>
  </el-card>
  
  <!-- IP访问详情表格 -->
  <el-card style="margin: 10px 0">
    <div class="operation-btns">
      <h3>IP访问详情</h3>
    </div>
    <el-table
        :data="ipAddressesList"
        :default-sort="{ prop: 'update_time', order: 'descending' }"
        style="margin: 10px 0"
        border
        v-loading="loading"
    >
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column
          label="序号"
          align="center"
          type="index"
          width="60"
      ></el-table-column>
      <el-table-column
          prop="id"
          label="ID"
          align="center"
          width="80"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          prop="ip_address"
          label="IP地址"
          align="center"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          prop="country"
          label="国家"
          align="center"
          width="100"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          prop="province"
          label="省份"
          align="center"
          width="100"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          prop="city"
          label="城市"
          align="center"
          width="100"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="访问时间"
          align="center"
          width="180"
          show-overflow-tooltip
          sortable
      >
        <template #default="{ row }">
          {{ formatTimeALL(row.update_time) }}
        </template>
      </el-table-column>
      <el-table-column
          prop="count"
          label="访问次数"
          align="center"
          width="100"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="{ row }">
          <el-button
              type="primary"
              size="small"
              icon="View"
              @click="showIpAddress(row.id)"
          >
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
    />
  </el-card>
</template>

<script setup lang="ts">
import { GetIpAddressListSync, getRecentIpAddressListSync } from "@/api/address";
import { onMounted, ref, computed } from "vue";
import { formatTime, formatTimeALL } from "@/utils/time.ts";
import { formatPast } from "@/utils/formatPast.ts";

// 页码和分页相关
let pageNo = ref<number>(1);
let pageSize = ref<number>(10);
let total = ref<number>(0);
let loading = ref<boolean>(false);

// 搜索关键字
let keyword = ref<string>('');

// IP地址数据
let ipAddressesList = ref<any[]>([]);
let ipAddressesListRecent = ref<any[]>([]);

// 过滤后的IP数据（用于搜索功能）
const filteredIpList = computed(() => {
  const start = (pageNo.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  
  // 如果有搜索关键字，先过滤数据
  const filtered = keyword.value
    ? ipAddressesList.value.filter(ip => 
        ip.ip_address.toLowerCase().includes(keyword.value.toLowerCase()) ||
        ip.province.toLowerCase().includes(keyword.value.toLowerCase()))
    : ipAddressesList.value;
  
  // 更新总数
  total.value = filtered.length;
  
  // 返回当前页的数据
  return filtered.slice(start, end);
});

// 组件挂载完毕获取IP数据
onMounted(async () => {
  await GetIpAddressList();
  await getRecentIpAddressList();
});

// 获取IP列表数据
const GetIpAddressList = async () => {
  loading.value = true;
  try {
    const res = await GetIpAddressListSync();
    if (res && res.data) {
      ipAddressesList.value = res.data;
      total.value = res.data.length;
    }
  } catch (error) {
    console.error('获取IP数据出错:', error);
  } finally {
    loading.value = false;
  }
};

// 获取最近访问记录
const getRecentIpAddressList = async () => {
  try {
    let res = await getRecentIpAddressListSync();
    if (res && res.data) {
      ipAddressesListRecent.value = res.data;
    }
  } catch (error) {
    console.error('获取最近访问记录出错:', error);
  }
};

// 查看IP详情
const showIpAddress = (id: any) => {
  console.log(id);
  // 这里可以实现查看详情的逻辑
};

// 处理页码变化
const handleCurrentChange = () => {
  // 页码变化时不需要重新请求数据，因为我们使用的是前端分页
};

// 分页大小变化处理
const handleSizeChange = () => {
  // 重置页码为1
  pageNo.value = 1;
};

// 搜索
const search = () => {
  // 重置页码
  pageNo.value = 1;
};

// 重置
const reset = () => {
  keyword.value = '';
  pageNo.value = 1;
  GetIpAddressList(); // 重新获取数据
};

// 表格行样式类名
const tableRowClassName = ({ row, rowIndex }) => {
  // 根据访问次数添加不同的类名
  if (row.count > 10) {
    return 'high-visit-row';
  } else if (row.count > 5) {
    return 'medium-visit-row';
  }
  return '';
};

// 获取渐变样式
const getGradientStyle = (index) => {
  // 基于 index 来生成不同的渐变颜色，使用更柔和的色调
  const gradients = [
    'linear-gradient(135deg, #8e96d6 0%, #b4b9e6 100%)', // 柔和主色调
    'linear-gradient(135deg, #a5abd6 0%, #c8cee6 100%)', // 柔和浅色
    'linear-gradient(135deg, #7a82c6 0%, #9da3d6 100%)', // 柔和中色
    'linear-gradient(135deg, #b4b9e6 0%, #d1d5f0 100%)', // 柔和亮色
    'linear-gradient(135deg, #6a71b6 0%, #8e96d6 100%)', // 柔和深色
  ];

  // 使用 index % gradients.length 来循环选择渐变
  return {
    background: gradients[index % gradients.length], // 设置渐变背景
  };
};
</script>

<style scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.operation-btns {
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header {
  margin-bottom: 15px;
}

.visit-list {
  padding: 0;
  list-style: none;
}

.ip-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  font-size: 16px;
  margin: 10px 0;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  color: white;
}

.ip-item:hover {
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
  transform: translateY(-1px);
}

.ip-info, .visit-info {
  display: flex;
  align-items: center;
}

.ip-address {
  font-weight: bold;
  color: rgba(255, 255, 255, 0.95);
  margin-right: 8px;
  font-size: 16px;
}

.province {
  color: rgba(255, 255, 255, 0.85);
  font-size: 14px;
}

.time {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.95);
  margin-right: 10px;
  font-weight: bold;
}

.page-access {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.85);
  font-style: italic;
}
</style>